springboot项目集成 swagger2, 并生成离线html和pdf文档(已解决pdf中文乱码问题)

您所在的位置:网站首页 asciidoctorj pdf 中文方块 springboot项目集成 swagger2, 并生成离线html和pdf文档(已解决pdf中文乱码问题)

springboot项目集成 swagger2, 并生成离线html和pdf文档(已解决pdf中文乱码问题)

2024-01-21 16:48| 来源: 网络整理| 查看: 265

背景 项目需要暴露API给其他项目团队调用,为方便接口联调,需提供API文档给服务调用方使用。 系统环境 开发语言: Java JDK:1.8 SpringBoot:latest springfox:2.9.2 操作步骤

1.集成swagger2、swagger2-ui

step1: 添加相关依赖jar包

io.springfox springfox-swagger2 ${springfox.version} io.springfox springfox-swagger-ui ${springfox.version}

step2: 项目代码增加swagger2相关配置,具体参考如下:

package com.xxx.xxx.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import springfox.documentation.annotations.ApiIgnore; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * @author XXX * @project XXX * @package com.xxx.xxx.config * @date 2020/10/19 16:31 */ @Configuration @EnableSwagger2 @ComponentScan("com.xxx.xxx.controller") public class Swagger2Config { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.xxx.xxx")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Demo Swagger2 RESTFul APIs") .description("api root:http://xxx.com.cn/api/xxx/v1") .termsOfServiceUrl("http://xxx.com.cn/") .contact("[email protected]") .version("1.0") .build(); } }

step3: 修改controller代码,示例如下:

package com.xxx.xxx.controller; import com.alibaba.fastjson.JSONObject; import com.xxx.xxx.common.RetMessage; import com.xxx.xxx.pojo.*; import com.xxx.xxx.service.MobileXxxAPIService; import com.xxxx.xxx.utils.CollectionUtils; import io.swagger.annotations.*; import io.swagger.annotations.Example; import io.swagger.annotations.ExampleProperty; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; /** * @author xxx * @project demo * @package com.xxx.xxx.controller * @description xxx数据API接口 * @date 2020/9/16 16:10 */ @Controller @RequestMapping("/mobile/xxx") @Api(value = "xxx 移动端api", description = "xxx 移动端api") public class MobileXxxAPIController { private final Logger logger = LoggerFactory.getLogger ( getClass ( ) ); @Autowired private MobileXxxAPIService mobileXxxAPIService; /** * 当前账户余额 * @param data * @return */ @ApiOperation(value = "当前账户余额", notes = "获取当前账户余额", httpMethod = "POST") @ApiResponses({ @ApiResponse(code = 201, message = "请求已经被实现"), @ApiResponse(code = 400, message = "请求参数有误"), @ApiResponse(code = 401, message = "用户验证失败"), @ApiResponse(code = 403, message = "服务器禁止访问"), @ApiResponse(code = 404, message = "请求资源未找到"), @ApiResponse(code = 500, message = "服务器内部解析出错")}) @RequestMapping(value = "/accountBalance") @ResponseBody public Object getAccountBalance(@RequestBody AccountBalanceRequestBody data) { return CollectionUtils.createMap ( RetMessage.DATA, mobileXxxAPIService.getAccountBalance (data.getOrg_id()), RetMessage.META, CollectionUtils.createMap ( RetMessage.MSG, RetMessage.MSGSUCCESS, RetMessage.CODE, RetMessage.CODESUCESS ) ); } }

2.安装插件生成离线html、PDF文档

step1:修改pom.xml,主要增加的配置项如下:

1.2.0 ${project.basedir}/src/docs/asciidoc ${project.build.directory}/swagger ${project.build.directory}/asciidoc/snippets ${project.build.directory}/asciidoc/generated ${project.build.directory}/asciidoc/html ${project.build.directory}/asciidoc/pdf ${swagger.output.dir}/swagger.json org.springframework.restdocs spring-restdocs-mockmvc io.github.swagger2markup swagger2markup-spring-restdocs-ext ${swagger2markup.version} test io.springfox springfox-staticdocs 2.6.1 org.springframework.boot spring-boot-starter-test test jcenter-snapshots jcenter http://oss.jfrog.org/artifactory/oss-snapshot-local/ jcenter-releases jcenter http://jcenter.bintray.com false org.springframework.boot spring-boot-maven-plugin org.apache.maven.plugins maven-surefire-plugin ${swagger.output.dir} ${swagger.snippetOutput.dir} io.github.swagger2markup swagger2markup-maven-plugin ${swagger2markup.version} io.github.swagger2markup swagger2markup-import-files-ext ${swagger2markup.version} io.github.swagger2markup swagger2markup-spring-restdocs-ext ${swagger2markup.version} ${swagger.input} ${generated.asciidoc.directory} ASCIIDOC TAGS ${project.basedir}/src/docs/asciidoc/extensions/overview ${project.basedir}/src/docs/asciidoc/extensions/definitions ${project.basedir}/src/docs/asciidoc/extensions/paths ${project.basedir}src/docs/asciidoc/extensions/security/ ${swagger.snippetOutput.dir} true test convertSwagger2markup org.asciidoctor asciidoctor-maven-plugin 1.5.6 org.asciidoctor asciidoctorj-pdf 1.5.0-alpha-zh.16 org.jruby jruby-complete 1.7.21 ${asciidoctor.input.directory} index.adoc book left 3 ${generated.asciidoc.directory} output-html test process-asciidoc html5 ${asciidoctor.html.output.directory} output-pdf test process-asciidoc pdf ${asciidoctor.pdf.output.directory} cn org.apache.maven.plugins maven-jar-plugin 3.1.0 true lib/ com.mskj.dop.ApplicationMain maven-dependency-plugin package copy-dependencies ${project.build.directory}/lib maven-resources-plugin 3.1.0 copy-resources prepare-package copy-resources ${project.build.outputDirectory}/static/docs ${asciidoctor.html.output.directory} ${asciidoctor.pdf.output.directory}

step2: 新增测试代码(生成html、PDF文件是在test阶段触发的) 具体的测试代码,参考如下:

package com.xxx.xxx; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.restdocs.AutoConfigureRestDocs; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.restdocs.operation.preprocess.Preprocessors; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import java.io.BufferedWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * @author xxx * @project xxx * @package com.xxx.xxx * @date 2020/10/21 14:03 */ @WebAppConfiguration @RunWith(SpringRunner.class) @AutoConfigureRestDocs(outputDir = "build/asciidoc/snippets") @SpringBootTest @AutoConfigureMockMvc public class Swagger2MarkupTest { @Autowired private MockMvc mockMvc; @Test public void createSpringfoxSwaggerJson() throws Exception { String outputDir = System.getProperty("io.springfox.staticdocs.outputDir"); MvcResult mvcResult = this.mockMvc.perform(get("/v2/api-docs") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andReturn(); MockHttpServletResponse response = mvcResult.getResponse(); String swaggerJson = response.getContentAsString(); Files.createDirectories(Paths.get(outputDir)); try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, "swagger.json"), StandardCharsets.UTF_8)) { writer.write(swaggerJson); } } }

step3: 项目源码目录下增加index.adoc文件 在这里插入图片描述 index.adoc文件内容:

include::{generated}/overview.adoc[] include::{generated}/paths.adoc[] include::{generated}/security.adoc[] include::{generated}/definitions.adoc[]

step4: 使用IDE mvn clean test触发文档构建

step5:查看PDF或者HTML文档,具体文档路径:

在这里插入图片描述

3.解决PDF中文乱码问题

具体参考【6】中的两种方式,笔者选择方式1 ⚠️下载asciidoctorj-pdf-1.5.0-alpha-zh.16.jar,请从【5】中提到的GitHub项目中下载 参考资料

[1].https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api [2].https://www.javazhiyin.com/57982.html [3].https://github.com/houko/SpringBootUnity [4].https://www.jianshu.com/p/033d650164c4 [5].https://blog.csdn.net/han_chuang/article/details/98748944 [6].https://www.hotbak.net/key/Swagger%E4%BD%BF%E7%94%A8%E4%B8%89%E8%A7%A3%E5%86%B3swagger2markup%E7%94%9F%E6%88%90%E7%9A%84%E7%A6%BB%E7%BA%BFpdfCSDN%E5%8D%9A%E5%AE%A2.html



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3